package com.whj.servicedriveruser.service.impl;

import com.whj.internalcommon.dto.Car;
import com.whj.internalcommon.dto.ResponseResult;
import com.whj.internalcommon.response.TerminalResponse;
import com.whj.internalcommon.response.TrackResponse;
import com.whj.servicedriveruser.mapper.CarMapper;
import com.whj.servicedriveruser.remote.ServiceMapClient;
import com.whj.servicedriveruser.service.CarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author whj
 * @since 2023-01-12
 */
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements CarService {

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private ServiceMapClient serviceMapClient;

    /**
     * 添加车辆信息 初始化 服务信息和轨迹信息
     *
     * @param car
     * @return
     */
    @Override
    public ResponseResult addCar(Car car) {

        LocalDateTime now = LocalDateTime.now();
        car.setUpdateTime(now);
        car.setCreateTime(now);

        //保存车辆
        carMapper.insert(car);

        //调用service—map服务，获取车辆的tid (根据车牌号创建)
        ResponseResult<TerminalResponse> responseResult = serviceMapClient.addTerminal(car.getVehicleNo(),car.getId()+"");
        String tid = responseResult.getData().getTid();
        car.setTid(tid);

        // 获得此车辆的轨迹id trid 调用service-map 服务
        ResponseResult<TrackResponse> trackResponseResponseResult = serviceMapClient.addTrack(tid);
        String trid = trackResponseResponseResult.getData().getTrid();
        String trname = trackResponseResponseResult.getData().getTrname();
        car.setTrid(trid);
        car.setTrname(trname);
        carMapper.updateById(car);
        return ResponseResult.success("");
    }

    /**
     * '
     * 根据id回去车辆信息
     *
     * @param carId
     * @return
     */
    @Override
    public ResponseResult getCarById(Long carId) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", carId);
        List<Car> cars = carMapper.selectByMap(map);
        return ResponseResult.success(cars.get(0));
    }
}
